#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
条文相关API
"""

from flask_restful import Resource, reqparse
from app.services.civil_code_service import civil_code_service
from app.utils.response_utils import create_response
from flask import request, current_app

class ArticleListAPI(Resource):
    """条文列表API"""
    
    def get(self):
        """获取条文列表"""
        try:
            # 解析查询参数
            parser = reqparse.RequestParser()
            parser.add_argument('part', type=str, help='编名称', location='args')
            parser.add_argument('chapter', type=int, help='章节号', location='args')
            parser.add_argument('page', type=int, default=1, help='页码', location='args')
            parser.add_argument('per_page', type=int, default=20, help='每页条数', location='args')
            
            args = parser.parse_args()
            
            # 如果指定了编，按章节查询
            if args['part']:
                result = civil_code_service.get_articles_by_chapter(
                    part=args['part'],
                    chapter_number=args['chapter'],
                    page=args['page'],
                    per_page=min(args['per_page'], 100)  # 限制最大每页条数
                )
                
                return create_response(
                    success=True,
                    data=result,
                    message=f"获取{args['part']}条文成功"
                )
            else:
                # 获取章节列表
                chapters = civil_code_service.get_chapters_list()
                return create_response(
                    success=True,
                    data={'chapters': chapters},
                    message="获取章节列表成功"
                )
                
        except Exception as e:
            current_app.logger.error(f"获取条文列表失败: {str(e)}")
            return create_response(
                success=False,
                error={
                    'code': 'ARTICLES_LIST_ERROR',
                    'message': '获取条文列表失败',
                    'details': str(e) if current_app.debug else '服务异常'
                },
                status_code=500
            )

class ArticleDetailAPI(Resource):
    """条文详情API"""
    
    def get(self, article_id):
        """获取条文详情"""
        try:
            article = civil_code_service.get_article_by_number(article_id)
            
            if article:
                return create_response(
                    success=True,
                    data=article,
                    message=f"获取法条{article_id}成功"
                )
            else:
                return create_response(
                    success=False,
                    error={
                        'code': 'ARTICLE_NOT_FOUND',
                        'message': f'法条{article_id}不存在',
                        'details': '请检查条文号是否正确'
                    },
                    status_code=404
                )
                
        except Exception as e:
            current_app.logger.error(f"获取条文详情失败: {str(e)}")
            return create_response(
                success=False,
                error={
                    'code': 'ARTICLE_DETAIL_ERROR',
                    'message': '获取条文详情失败',
                    'details': str(e) if current_app.debug else '服务异常'
                },
                status_code=500
            )

class ChapterListAPI(Resource):
    """章节列表API"""
    
    def get(self):
        """获取章节列表"""
        try:
            chapters = civil_code_service.get_chapters_list()
            return create_response(
                success=True,
                data={'chapters': chapters},
                message="获取章节列表成功"
            )
            
        except Exception as e:
            current_app.logger.error(f"获取章节列表失败: {str(e)}")
            return create_response(
                success=False,
                error={
                    'code': 'CHAPTERS_LIST_ERROR',
                    'message': '获取章节列表失败',
                    'details': str(e) if current_app.debug else '服务异常'
                },
                status_code=500
            )

class ChapterArticlesAPI(Resource):
    """章节条文API"""
    
    def get(self, chapter_number):
        """获取指定章节的条文"""
        try:
            # 解析查询参数
            parser = reqparse.RequestParser()
            parser.add_argument('part', type=str, required=True, help='编名称不能为空')
            parser.add_argument('page', type=int, default=1, help='页码')
            parser.add_argument('per_page', type=int, default=20, help='每页条数')
            
            args = parser.parse_args()
            
            result = civil_code_service.get_articles_by_chapter(
                part=args['part'],
                chapter_number=chapter_number,
                page=args['page'],
                per_page=min(args['per_page'], 100)
            )
            
            return create_response(
                success=True,
                data=result,
                message=f"获取{args['part']}第{chapter_number}章条文成功"
            )
            
        except Exception as e:
            current_app.logger.error(f"获取章节条文失败: {str(e)}")
            return create_response(
                success=False,
                error={
                    'code': 'CHAPTER_ARTICLES_ERROR',
                    'message': '获取章节条文失败',
                    'details': str(e) if current_app.debug else '服务异常'
                },
                status_code=500
            )
